import amapFile from '@/js_sdk/amap-wx.130.js';

const aMapKey = '7813095de7b645f2fc0159c94a47144b';
let myAmapFun = null;

// 初始化高德地图
const initAmap = () => {
  myAmapFun = new amapFile.AMapWX({ key: aMapKey });
};

//转换成省市区 latitude纬度，long经度
export const getAddress = fn => {
  // fn(null, { 'city': '北京' });
  // return;

  // 保证整个APP运行期间只初始化一次，并且在使用到的时候才进行初始化，避免浪费内存占用
  if (!myAmapFun) {
    initAmap();
  }
  myAmapFun.getRegeo({
    // location: "" + longitude + "," + latitude + "", //location的格式为'经度,纬度'
    success: data => {
      console.log('转换成省市', data);
      let { province, city, district } = data[0].regeocodeData.addressComponent;
      city = (city && city.length > 0 ? city[0] : province).replace('市', '');
      fn(null, { province, city, district });
    },
    fail: info => {
      console.log('location, ', info);
      fn(info, {});
    },
  });
};

/**
 * 通过高德SDK获取经纬度
 * @param {*} fn
 */
export const getLongitudeLatitude = () => {
  // 保证整个APP运行期间只初始化一次，并且在使用到的时候才进行初始化，避免浪费内存占用
  if (!myAmapFun) {
    initAmap();
  }
  return new Promise((resolve, reject) => {
    myAmapFun.getRegeo({
      success: res => {
        const { latitude, longitude } = res[0] || {};
        resolve({
          latitude,
          longitude,
        });
      },
      fail: err => {
        resolve({});
      },
    });
  });
};
